import java.util.*;

public class Leetcode {
}

//leetcode:675:为高尔夫比赛砍树
class Solution {
    int m,n;
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    public int cutOffTree(List<List<Integer>> forest) {
        m = forest.size();
        n = forest.get(0).size();
        //将树的下标放入表中
        List<int[]> trees = new ArrayList<>();
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(forest.get(i).get(j) > 1){
                    trees.add(new int[]{i,j});
                }
            }
        }

        //将表中的下标按照对应的值进行排序
        Collections.sort(trees,(a,b) -> {
            return forest.get(a[0]).get(a[1]) - forest.get(b[0]).get(b[1]);
        });

        //按照排序顺序依次进行砍树
        int ret = 0;
        int bx = 0, by = 0;
        for(int[] tree : trees){
            int x = tree[0], y = tree[1];
            int step = bfs(forest,bx,by,x,y);
            if(step == -1) return -1;
            ret += step;
            bx = x;
            by = y;
        }
        return ret;
    }

    //一棵树到下一棵树的最短路径
    public int bfs(List<List<Integer>> forest,int bx, int by, int ex,int ey){
        if(bx == ex && by == ey) return 0;

        Queue<int[]> q = new LinkedList<>();
        boolean[][] visits = new boolean[m][n];
        q.add(new int[]{bx,by});
        visits[bx][by] = true;

        int step = 0;
        while(!q.isEmpty()){
            step++;
            int sz = q.size();
            while(sz-- != 0){
                int[] s = q.poll();
                int a = s[0], b = s[1];
                for(int k = 0; k < 4; k++){
                    int x = a + dx[k], y = b + dy[k];
                    if(x >= 0 && x < m &&  y >= 0 && y < n && forest.get(x).get(y) != 0 && !visits[x][y]){
                        if(x == ex && y == ey) return step;
                        q.add(new int[]{x,y});
                        visits[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
}